﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class 数据算法_RSA加解密 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider( );
   var d=   rsa.Decrypt(System.Text.UTF8Encoding.UTF8.GetBytes("什么东东哦"), true);

    }


}

namespace System {

    public static class RsaHelper 
    {
         /// <summary>
    /// 编码数据
    /// </summary>
    /// <param name="s">需要加密码的字符串</param>
    /// <param name="key">key</param>
    /// <returns>返回编码后的数据</returns>
    public static string RSADecrypt(this string s, string key)
    {
        string result = null;
        if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");
        if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
        CspParameters cspp = new CspParameters();
        cspp.KeyContainerName = key;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);


        rsa.PersistKeyInCsp = true;
        string[] decryptArray = s.Split(new string[] { "-" }, StringSplitOptions.None);
        byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (a => Convert.ToByte(byte.Parse(a, System.Globalization.NumberStyles.HexNumber))));
        byte[] bytes = rsa.Decrypt(decryptByteArray, true);
        result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
        return result;
    }
    /// <summary>
    /// 解析RSA编码
    /// </summary>
    /// <param name="s">需要解析的字符串</param>
    /// <param name="key">key</param>
    /// <returns>返回数据</returns>
    public static string RSAEncrypt(this string s, string key)
    {
        if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");
        if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
        CspParameters cspp = new CspParameters();
        cspp.KeyContainerName = key;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
        rsa.PersistKeyInCsp = true;
        byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(s), true);
        return BitConverter.ToString(bytes);
    }

}
}